<template>
  <WidgetBase :data="data" :clearable="!!data.value" @drop.native.stop v-loading="loading">
    <div
      v-if="image"
      class="fa-widget-image__img"
      :style="{ backgroundImage: `url(${image})` }"
      @click="areaClick"
    ></div>

    <WidgetPlaceholder v-else-if="!data.isDone" :data="data" vertical @click.native="areaClick" />

    <template v-if="data.isUse">
      <input ref="input" class="fa-widget-image__input" type="file" :accept="accept" @change="fileChange" />

      <WidgetPlaceholder
        class="fa-widget-image__mask"
        :data="data"
        vertical
        :icon="image ? 'el-icon-refresh-right' : 'fa-icon-upload'"
        :text="image ? '重新上传' : '上传图片'"
        @click.native="areaClick"
      />
    </template>
  </WidgetBase>
</template>

<script lang="ts">
import { defineComponent, inject, ref, toRef, toRefs, watch } from 'vue'
import { ImageAspectMap, Viewer } from '@/types'
import { Widget } from '@/models'
import WidgetBase from '@/components/widget-base/WidgetBase.vue'
import WidgetPlaceholder from '@/components/widget-base/WidgetPlaceholder.vue'
import useUpload from './useUpload'

/** 图片控件 */
export default defineComponent({
  name: 'FaWidgetImage',

  components: { WidgetBase, WidgetPlaceholder },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    }
  },

  setup(props) {
    const data = toRef(props, 'data')

    /** 合同控件 */
    const viewer = inject('Viewer') as Viewer

    /** 同步更新比例 */
    watch(
      () => ImageAspectMap.get(props.data.image.aspect)?.value ?? 0,
      ratio => {
        props.data.aspectRatio = ratio
      },
      { immediate: true }
    )

    return useUpload({
      data,
      viewer: ref(viewer)
    })
  }
})
</script>

<style lang="scss">
.fa-widget-image {
  &__img {
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
  }

  &__input {
    position: absolute;
    width: 0;
    height: 0;
    opacity: 0;
  }

  &__mask {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: #fff;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;

    .fa-widget-image:hover & {
      opacity: 1;
    }
  }
}
</style>
